
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import control.ticketBooking;
import cs4280.bean.*;
import cs4280.dao.*;

public final class mySessionTracker implements
        HttpSessionListener, HttpSessionAttributeListener {

    ArrayList<Ticket> tickets = new ArrayList<Ticket>();

    public void sessionCreated(HttpSessionEvent se) {
// code to be executed when a session is created
        CounterDAO counterDAO=new CounterDAO();
        Counter counter=counterDAO.getCounter();
        counter.getCountIncrement();
        counterDAO.changeCount(counter.getCount());
    }

    public void sessionDestroyed(HttpSessionEvent se) {
// code to be execute before a session is destroyed
        this.doReleaseTicket();
    }

    public void attributeAdded(HttpSessionBindingEvent e) {
// code to be executed when an attribute is added
        String name = e.getName();
        if (name.equalsIgnoreCase("ticketsReserve")) {

            ArrayList<Ticket> ticketsTemp = (ArrayList<Ticket>) e.getValue();
            Iterator<Ticket> it = ticketsTemp.iterator();
            while (it.hasNext() != false) {
                Ticket ticketT = it.next();
                tickets.add(ticketT);
            }
            HttpSession session = e.getSession();
            session.setMaxInactiveInterval(300);
        }
    }

    public void attributeReplaced(HttpSessionBindingEvent e) {
// code to be executed when the value of an attribute is replaced
    }

    public void attributeRemove(HttpSessionBindingEvent e) {
// code to be executed when an attribute is removed
    }

    public void attributeRemoved(HttpSessionBindingEvent event) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void doReleaseTicket() {        ScreeningDAO screeningDAO = new ScreeningDAO();
        String temp1;
        String temp2;
        int seatNo;
         String seatingS;
        char a = '0';

        Iterator<Ticket> it = tickets.iterator();
        while (it.hasNext() != false) {
            Ticket ticketT = it.next();
            Screening screening = new Screening();
            screening = screeningDAO.getScreening(ticketT.getScreeningid());
            seatingS = screening.getSeating();
            seatNo=ticketT.getSeatingNo();
            if (seatNo == 0) {
                seatingS = a + seatingS.substring(1);
            } else if (seatNo == seatingS.length() - 1) {
                seatingS = seatingS.substring(0, seatNo) + a;
            } else {
                temp1 = seatingS.substring(0, seatNo);
                temp2 = seatingS.substring(seatNo + 1, seatingS.length());
                seatingS = temp1 + a + temp2;
            }
            screeningDAO.setSeating(ticketT.getScreeningid(), seatingS);

        }

    }
}
